/**
 * 
 * @authors Your Name (you@example.org)
 * @date    2015-05-18 00:26:19
 * @version $Id$
 */
'use strict';

define(['angular', 'services', 'global/constants', 'global/url'], function(angular, services, constants, url) {
	var flightDirectives = angular.module('flightAdminApp.directives', ['flightAdminApp.services']);
	flightDirectives.directive('switchNav', function() {
		return {
	        link: function(scope, ele, attrs, c) {
		        var self = $(ele);
		        ele.on('click', function() {
		            self.parent().find('li').removeClass('active');
		            self.addClass('active')
		        });
	        }
        }
	});

	flightDirectives.directive('adminLogout', ['AdminService', function(AdminService) {
		return {
	        link: function(scope, ele, attrs, c) {
		        var self = $(ele);
		        ele.on('click', function() {
		            AdminService.Admin.logout();
					window.location.href = constants.pages.login;
		        });
	        }
        }
	}]);

	flightDirectives.directive('adminLogin', ['UtilService', 'AdminService', function(UtilService, AdminService) {

		return {
	        link: function(scope, ele, attrs, c) {
		        var self = $(ele);
		        ele.on('click', function() {
		            var params = { 'username' : scope.username,
		              			   'password' : scope.password
		              			 }
		            
	    		    AdminService.login(params).success(function(response, status) {
	  		            if (response.jsonResponse.statusCode == constants.responseCode.SUCCESS) {
	  		            	scope.$root.accessToken = response.jsonResponse.response.accessToken;
	  		            	scope.$root.login = true;
	  		            	AdminService.Admin.setName(response.jsonResponse.response.name);
	  		            	AdminService.Admin.setAccessToken(response.jsonResponse.response.accessToken, scope.rememberMe);
                            AdminService.Admin.init();
	  		            	window.location.href = constants.pages.dashboard;
	  	                } else {
	  	                	var errorMsg = response.jsonResponse.additionalInfo;
	  	                	errorMsg = errorMsg.substr(errorMsg.lastIndexOf('\n'), errorMsg.length -1);
	  	                	UtilService.showErrorMessage('Login Failed', errorMsg);
	  	                }
                    });
		        });
	        }
        }
	}]);

    /***************************************************** Mission module  ****************************************************************/

	flightDirectives.directive('adminEditMission', ['UtilService', function(UtilService) {
		return {
	        link: function(scope, ele, attrs, c) {
		        var self = $(ele);
		        ele.on('click', function(e) {
		        	var $selectMission = $('#misson-table input[name=select-single-mission]:checked');
		        	if ($selectMission.length) {
				        var $mission = $selectMission.parent().parent();
				        var missionId = $mission.find('.missionId').text(), missionName = $mission.find('.missionName').text();
				        $('#edit-mission-modal input[name=missionName]').val(missionName);
				        $('#edit-mission-modal button').data('id', missionId);
				        UtilService.showModal($('#edit-mission-modal'));
		        	} else {
		        		UtilService.showModal($('#mission-warning'));
		        	}
		        	
		        });
	        }
        }
	}]);

	flightDirectives.directive('adminDeleteMission', ['UtilService', function(UtilService) {
		return {
	        link: function(scope, ele, attrs, c) {
		        var self = $(ele);
		        ele.on('click', function(e) {
		        	var $selectMission = $('#misson-table input[name=select-single-mission]:checked');
		        	if ($selectMission.length) {
				        var $mission = $selectMission.parent().parent();
				        var missionId = $mission.find('.missionId').text();
				        $('#delete-mission-modal .delete-mission-btn').data('id', missionId);
				        UtilService.showModal($('#delete-mission-modal'));
		        	}  else {
		        		UtilService.showModal($('#mission-warning'));
		        	}
		        	
		        });
	        }
        }
	}]);

	flightDirectives.directive('adminMissionData', ['UtilService', 'MissionService', '$compile', function(UtilService, MissionService, $compile) {
		var $scope;

		function _renderMissionPager (data) {
			var $record = $('.mission-container .mission-total-record'),
			    $element = $('.mission-container .mission-pager-container');
			UtilService.renderPagerContainer($element, $record, data, $scope, $compile);
		}

		function _changeMissionPagesize (event) {
	    	var $ele = $(this), params = {
		        	'accessToken': $scope.accessToken,
		        	'filter': {
			        	'pagesize': 10,
			        	'pno': 1,
			        	'search': ''
			        }
                };
	    	params.filter.pagesize = $ele.data('value');
	    	params.filter.pno = $scope.missions.currentPage;
	    	_renderMissionList(params);
        }

	    function _selectAllMissions (event) {
	    	var $ele = $(this);
	    	if ($ele.prop('checked')) {
	    	    $('.select-single-record').prop('checked', 'checked');
	    	} else {
	    		$('.select-single-record').each(function() {
	    			$(this).prop('checked', false);
	    		})
	    	}
	    }

	     function _renderMissionList (params) {
	    	MissionService.listMissions(params).success(function(response, status) {
	  		    if (response.jsonResponse.statusCode == constants.responseCode.SUCCESS) {
	  		       $scope.missions = response.jsonResponse.response.data;
	  	        } else if (response.statusCode == constants.responseCode.LOGIN_ANOTHER_DEVICE) {
	  	           AdminService.Admin.logout();
	  	           window.location.href = constants.pages.login;
	  	        }
            });
	    }

	    function _closeQuestWarning () {
	    	$('#quests-modal').css('z-index', 1110);
	    }

		return {
	        link: function(scope, ele, attrs, c) {
		        var self = $(ele);
		        $scope = scope;
		        scope.$watch('missions', function(newVal, oldVal) {
		        	scope.missions = newVal;
		            if (newVal) {
		            	_renderMissionPager(newVal);
		            }
		        });

		        $('.mission-container .mission-page-list').on('click', '.am-selected-list li', _changeMissionPagesize);
			    $('.mission-container #misson-table').on('click', '.select-all-mission', _selectAllMissions);
			    $('#quest-warning').on('click', '.am-modal-footer span', _closeQuestWarning);
	        }
        }
	}]);

	flightDirectives.directive('adminMissionQuests', ['MissionService', 'AdminService', function(MissionService, AdminService) {
		return {
	        link: function(scope, ele, attrs, c) {
		        var self = $(ele);
		        scope.$root.$watch('quests', function(newVal, oldVal) {
		        	scope.quests = newVal;
		        });
		        ele.on('click', function(e) {

		        	var filter = {
		        		'pno': 1,
		        		'pagesize': 10
		        		}, missionId = self.data('missionid');
		        	$('#quests-modal').data('id', missionId);
		        	MissionService.listQuests({'missionId': missionId, 'filter': filter, 'accessToken': ''}).success(function(response, status) {
		        		if (response.jsonResponse.statusCode == constants.responseCode.SUCCESS) {
				  		    scope.$root.quests = response.jsonResponse.response.data;
				  	    } else if (response.statusCode == constants.responseCode.LOGIN_ANOTHER_DEVICE) {
				  	        AdminService.Admin.logout();
						  	window.location.href = constants.pages.login;
				  	    }
		        	});
		        });
	        }
        }
	}]);


	flightDirectives.directive('adminEditQuest', ['UtilService', 'MissionService', function(UtilService, MissionService) {
		return {
	        link: function(scope, ele, attrs, c) {
		        var self = $(ele);
		        ele.on('click', function(e) {
		        	var $selectQuest = $('#quest-table input[name=select-single-quest]:checked');
		        	if ($selectQuest.length) {
				        var $quest = $selectQuest.parent().parent();
				        var questId = $quest.find('.questId').text(),
				        	missionId = $('#quests-modal').data('id');
				        $('#edit-quest-modal button').data('id', questId);
				        MissionService.getQuest({'questId': questId, 'missionId': missionId, 'accessToken': scope.accessToken}).success(function(response, status){
				        	if (response.jsonResponse.statusCode == constants.responseCode.SUCCESS) {
				        		scope.quest = response.jsonResponse.response.data;
				        	}
				        })
				        UtilService.showModal($('#edit-quest-modal'));
		        	} else {
		        		UtilService.showModal($('#quest-warning'));
		        	}
		        	
		        });
	        }
        }
	}]);


	flightDirectives.directive('adminOperateQuest', ['UtilService', 'MissionService', 'AdminService', function(UtilService, MissionService, AdminService) {
		var $scope;

		function _refreshMissionQuests () {
			var filter = {'pagesize': 10 , 
							'pno': 1 , 
							'search': ''
						 },
			missionId = $('#quests-modal').data('id');
		    MissionService.listQuests({'accessToken': $scope.accessToken, 'filter': filter, 'missionId': missionId}).success(function(response, status) {
		  		if (response.jsonResponse.statusCode == constants.responseCode.SUCCESS) {
		  		    $scope.quests = response.jsonResponse.response.data;
		  	    } else if (response.statusCode == constants.responseCode.LOGIN_ANOTHER_DEVICE) {
		  	        AdminService.Admin.logout();
				  	window.location.href = constants.pages.login;
		  	    }
	        });
	    }

		function _operateQuest (quest) {
			MissionService.operateQuest({'accessToken': $scope.accessToken, 'operate': JSON.stringify(quest)}).success(function(response, status) {
				if (response.jsonResponse.statusCode == constants.responseCode.SUCCESS) {
				    if (response.jsonResponse.response.meta.code == constants.responseCode.HTTP_OK) {
						_refreshMissionQuests();
						$('#quests-modal').css('z-index', 1110);
						$scope.quest = null;

				    }
				} else if (response.statusCode == constants.responseCode.LOGIN_ANOTHER_DEVICE) {
				  	AdminService.Admin.logout();
				  	window.location.href = constants.pages.login;        
				}
			})
		}

		return {
	        link: function(scope, ele, attrs, c) {
	        	$scope = scope;
		        var self = $(ele);
		        ele.on('click', function(e) {
		        	var oper = self.data('oper'), operationVo = {
						'oper': oper, 
						'id': self.data('id'), 
						'data': {
						}
					};	
					
					$scope.quest.missionId = $('#quests-modal').data('id');
					if(constants.operation.ADD === oper) {
						UtilService.validateForm('#add-quest-modal');
						if($('#add-quest-modal').data('amui.validator').isFormValid()) {
							operationVo.data = $scope.quest;
							_operateQuest(operationVo);
							UtilService.clearValidForm('#add-quest-modal');
							$('#add-quest-modal .am-close-spin').click();
						};
					} else if (constants.operation.EDIT === oper) {
						UtilService.validateForm('#edit-quest-modal');
						if($('#edit-quest-modal').data('amui.validator').isFormValid()) {
							operationVo.data = $scope.quest;
							_operateQuest(operationVo);
							UtilService.clearValidForm('#edit-quest-modal');
							$('#edit-quest-modal .am-close-spin').click();
						};
					} else {
						$('.am-close-spin').click();
						_operateQuest(operationVo);
					}

		        });
	        }
        }
	}]);


	flightDirectives.directive('adminOperateMission', ['UtilService', 'MissionService', function(UtilService, MissionService) {
		var $scope;
		function _refreshMissions () {
			var pagesize = $('.am-selected-list .am-checked').data('value'), 
				filter = {'pagesize': pagesize , 
							'pno': 1 , 
							'search': ''
						 };
		    MissionService.listMissions({'accessToken': $scope.accessToken, 'filter': filter}).success(function(response, status) {
		  		if (response.jsonResponse.statusCode == constants.responseCode.SUCCESS) {
		  		    $scope.missions = response.jsonResponse.response.data;
		  	    } else if (response.statusCode == constants.responseCode.LOGIN_ANOTHER_DEVICE) {
		  	          
		  	    }
	        });
	    }

		function _operateMissions (mission) {
			MissionService.operateMission({'accessToken': $scope.accessToken, 'operate': JSON.stringify(mission)}).success(function(response, status) {
				if (response.jsonResponse.statusCode == constants.responseCode.SUCCESS) {
				  	if (response.jsonResponse.response.meta.code == 200) {
						$('.am-close-spin').click();
						_refreshMissions();
				    }
				} else if (response.statusCode == constants.responseCode.LOGIN_ANOTHER_DEVICE) {
				  	         
			    }
			})
		}

		return {
	        link: function(scope, ele, attrs, c) {
	        	$scope = scope;
		        var self = $(ele);
		        ele.on('click', function(e) {
		        	var oper = self.data('oper'), operationVo = {
						'oper': oper, 
						'id': self.data('id'), 
						'data': {
							'name': ''
						}
					};	

					if(constants.operation.ADD === oper) {
						UtilService.validateMissionForm('#add-mission-modal');
						if($('#add-mission-modal').data('amui.validator').isFormValid()) {
							operationVo.data.name = $scope.missionName;
							_operateMissions(operationVo);
						};
					} else if (constants.operation.EDIT === oper) {
						UtilService.validateMissionForm('#edit-mission-modal')
						if($('#edit-mission-modal').data('amui.validator').isFormValid()) {
							operationVo.data.name = $('#edit-mission-modal input[name=missionName]').val();
							_operateMissions(operationVo);
						};
					} else {
						_operateMissions(operationVo);
					}

		        });
	        }
        }
	}]);


    /***************************************************** Active code module  ****************************************************************/
	flightDirectives.directive('adminActiveData', ['UtilService', 'ActiveCodeService', '$compile', function(UtilService, ActiveCodeService, $compile) {
		var $scope;
		function _renderActivePager (data) {
			var $record = $('.active-container .active-code-total-record'),
			    $element = $('.active-container .active-pager-container');
			UtilService.renderPagerContainer($element, $record, data, $scope, $compile);
		}

	     function _forwardActivePages (event) {
	    	var $ele = $(this), pno = $ele.find('a').text(),
	    		pagesize = $('.am-selected-list .am-checked').data('value');
	    	filter.pagesize = pagesize;
	    	filter.pno = pno;
	    	_renderActiveCodeList(filter);
	    }

		function _changeActivePagesize (event) {
	    	var $ele = $(this), params = {
		        	'accessToken': $scope.accessToken,
		        	'filter': {
			        	'pagesize': 10,
			        	'pno': 1,
			        	'search': ''
			        }
                };
	    	params.filter.pagesize = $ele.data('value');
	    	params.filter.pno = $scope.activeCodes.currentPage;
	    	_renderActiveCodeList(params);
        }

        function _renderActiveCodeList (params) {
	    	ActiveCodeService.listActiveCodes(params).success(function(response, status) {
			  		if (response.jsonResponse.statusCode == constants.responseCode.SUCCESS) {
			  		    $scope.activeCodes = response.jsonResponse.response.data;
			  	    } else if (response.statusCode == constants.responseCode.LOGIN_ANOTHER_DEVICE) {
			  	        AdminService.Admin.logout();
			  	        window.location.href = constants.pages.login;
			  	    }
		    });
	    }

	  	function _changeActive (event) {
	    	var $ele = $(this), id = $ele.data('id');
	    	ActiveCodeService.updateCodeStatus({'baseId': id}).success(function(data){
	    		if (data.result) {
	    			$ele.find('span').text('Used');
	    			$ele.removeClass('am-btn-danger');
	    			$ele.addClass('am-btn-success');
	    		} else {
	    			$ele.find('span').text('Unused');
	    			$ele.removeClass('am-btn-success');
	    			$ele.addClass('am-btn-danger');
	    		}
	    	});
	    }

		return {
	        link: function(scope, ele, attrs, c) {
		        var self = $(ele);
		        $scope = scope;
		        scope.$watch('activeCodes', function(newVal, oldVal) {
		        	scope.activeCodes = newVal;
		            if (newVal) {
		            	_renderActivePager(newVal);
		            }
		        });	
			    $('.active-pager-container').on('click', '.active-pno', _forwardActivePages);
		        $('.active-page-list').on('click', '.am-selected-list li', _changeActivePagesize);
		        $('.active-container .am-table').on('click', '.am-active-status', _changeActive);
	        }
        }
	}]);

 /***************************************************** store module  ****************************************************************/

	flightDirectives.directive('adminStoreData', ['UrlService', 'UtilService', '$compile', 'StoreService',
				function(UrlService, UtilService, $compile, StoreService) {
		var $scope, 
			filter = {
				'pagesize': 10,
				'pno': 1,
				'search': ''
			}
		function _renderStorePager (data) {
			var $record = $('.store-container .store-total-record'),
			    $element = $('.store-container .store-pager-container');
			UtilService.renderPagerContainer($element, $record, data, $scope, $compile);
		}

		function _changeStorePages (event) {
	    	var $ele = $(this);
	    	filter.pagesize = $ele.data('value');
	    	_renderStoreList(filter);
        }

        function _searchStorePages (event) {
	    	var $ele = $(this), search = $ele.val(), 
	    		pagesize = $('.am-selected-list .am-checked').data('value');
	    	filter.pagesize = pagesize;
	    	filter.search =  search;
	    	_renderStoreList(filter);
	    }

	     function _forwardStorePages (event) {
	    	var $ele = $(this), pno = $ele.find('a').text(), 
	    	    pagesize = $('.am-selected-list .am-checked').data('value');
	        filter.pagesize = pagesize;
	    	filter.pno =  pno;
	    	_renderStoreList(filter);
	    }

	    function _renderStoreList (filter) {
	    	var apiURL = url.storeListURL() +'?accessToken='+$scope.accessToken+'&filter=' + escape(JSON.stringify(filter));
	    	UrlService.doRequest(apiURL, 'GET').success(function(response, status) {
	  		    if (response.jsonResponse.statusCode == constants.responseCode.SUCCESS) {
	  		       $scope.stores = response.jsonResponse.response.data;
	  	        } else if (response.statusCode == constants.responseCode.LOGIN_ANOTHER_DEVICE) {
	  	          
	  	        }
            });
	    }

	    function _selectAllStores (event) {
	    	var $ele = $(this);
	    	if ($ele.prop('checked')) {
	    	    $('.select-single-record').prop('checked', 'checked');
	    	} else {
	    		$('.select-single-record').each(function() {
	    			$(this).prop('checked', false);
	    		})
	    	}
	    }

	    function _changeStorePagesize (event) {
	    	var $ele = $(this), params = {
		        	'accessToken': $scope.accessToken,
		        	'filter': {
			        	'pagesize': 10,
			        	'pno': 1,
			        	'search': ''
			        }
                };
	    	params.filter.pagesize = $ele.data('value');
	    	$scope.stores.pagesize = $ele.data('value');
	    	params.filter.pno = $scope.stores.currentPage;
	    	_renderStoreList(params);
        }
        function _editStores(){
        	$('#edit-store-modal').modal();
        }

		return {
	        link: function(scope, ele, attrs, c) {
		        var self = $(ele);
		        $scope = scope;
		        scope.$watch('stores', function(newVal, oldVal) {
		        	scope.stores = newVal;
		            if (newVal) {
		            	_renderStorePager(newVal);
		            }
		        });

		        $('.store-container .store-page-list').on('click', '.am-selected-list li', _changeStorePages);
			    $('.store-container .store-filter').on('keyup', '.search-store', _searchStorePages);
			    $('.store-container .store-pager-container').on('click', '.active-pno', _forwardStorePages);
			    $('.store-container .select-all-store').on('click', _selectAllStores);
			    $('.store-page-list').on('click', '.am-selected-list li', _changeStorePagesize);
			    $('.store-container').on('click', '.store-edit', _editStores);
	        }
        }
	}]);


	
	flightDirectives.directive('adminEditStore', ['UrlService', 'UtilService', '$compile', '$timeout', function(UrlService, UtilService, $compile, $timeout) {
		return {
	        link: function(scope, ele, attrs, c) {
		        var self = $(ele);
		        ele.on('click', function(e) {   
		        	var $selectStore = $('#store-table input[name=select-single-store]:checked');
		        	if ($selectStore.length) {	
				        var $store = $selectStore.parent().parent();
				        var storeId = $store.find('.storeId').text(), storeName = $store.find('.storeItemName').text();
				        var storeSku = $store.find('.storeSku').text(),storePrice = $store.find('.storePrice').text();
				        var storeQuantity = $store.find('.storeQuantity').text();
				        $('#edit-store-modal input[name=storeItemName]').val(storeName);
				        $('#edit-store-modal input[name=storeSku]').val(storeSku);
				        $('#edit-store-modal input[name=storePrice]').val(storePrice);
				        $('#edit-store-modal input[name=storeQuantity]').val(storeQuantity);
				        scope.id = storeId;
				        $timeout(function() {
				        	$('#edit-store-modal input[name=storeDescription]').val($store.find('.storeDescription').text());
				        	$('#edit-store-modal').modal();
				        });
				       
				       
		        	} else {
		        		$('store-warning').modal({
		        			width: 250,
		        			height: 130
		        		});
		        	}
		        	
		        });
	        }
        }
	}]);
	

	flightDirectives.directive('adminDeleteStore', function() {
		return {
	        link: function(scope, ele, attrs, c) {
		        var self = $(ele);
		        ele.on('click', function(e) {
		        	var $selectStore = $('#store-table input[name=select-single-store]:checked');
		        	if ($selectStore.length) {
				        var $store = $selectStore.parent().parent();
				        var storeId = $store.find('.storeId').text();
				        $('#delete-store-modal .delete-store-btn').data('id', storeId);
				        $('#delete-store-modal').modal({
				        	width: 400,
				        	height: 130
				        });
				       
		        	} else {
		        		$('#store-warning').modal({
		        			width: 250,
		        			height: 130
		        		});
		        	}
		        	
		        });
	        }
        }
	});

	flightDirectives.directive('adminOperateStore', ['UrlService','StoreService',function(UrlService, StoreService) {
		var $scope;
		
		function _refreshStore () {
			var params = {
		        	'accessToken': $scope.accessToken,
		        	'filter': {
			        	'pagesize':  $scope.stores.pagesize,
			        	'pno':  $scope.stores.currentPage,
			        	'search': $scope.search
			        }
                };
	    	StoreService.listStores(params).success(function(response, status) {
	  		    if (response.jsonResponse.statusCode == constants.responseCode.SUCCESS) {
	  		       $scope.stores = response.jsonResponse.response.data;
	  	        } else if (response.statusCode == constants.responseCode.LOGIN_ANOTHER_DEVICE) {
	  	          
	  	        }
            });
	    }

		function _operateStore (store) {
			var apiURL = url.storeUpdateURL() +'?accessToken='+$scope.accessToken+'&operate=' + JSON.stringify(store);
		    UrlService.doRequest(apiURL, 'POST').success(function(response, status) {
			  	if (response.jsonResponse.statusCode == constants.responseCode.SUCCESS) {
			  		if (response.jsonResponse.response.meta.code == 200) {
					  	$('.am-close-spin').click();
					  	_refreshStore();
			  		}
			  	} else if (response.statusCode == constants.responseCode.LOGIN_ANOTHER_DEVICE) {
			  	         
			  	}
	        });
		}

		function _validateStoreForm (formId) {
			$(formId).validator({
				onValid: function(validity) {
					$(validity.field).closest('.am-form-group').find('.am-alert').hide();
				},
				onInValid: function(validity) {
					var $field = $(validity.field);
					var $group = $field.closest('.am-form-group');
					var $alert = $group.find('.am-alert');
					var msg = $field.data('validationMessage') || this.getValidationMessage(validity);

					if (!$alert.length) {
						$alert = $('<div class="am-alert am-alert-danger"></div>').hide().
						appendTo($group);
					}
					$alert.html(msg).show();
				}
  			});
		}

		return {
	        link: function(scope, ele, attrs, c) {
	        	$scope = scope;
		        var self = $(ele);
		        
		        
		        ele.on('click', function(e) {
		        	var storeQuantity = $('#edit-store-modal input[name=storeQuantity]').val();
		        	var storePrice = $('#edit-store-modal input[name=storePrice]').val();
		        	var oper = self.data('oper'), operationVo = {
						'oper':oper, 
						'id': scope.id, 
						'data': {
							'itemName': scope.storeItemName ,
							'sku': scope.storeSku,
							'quantity': scope.storeQuantity || storeQuantity,
							'price': scope.storePrice || storePrice
						}
					};	

					if(constants.operation.ADD === oper) {
						_validateStoreForm('#add-store-modal');
						if($('#add-store-modal').data('amui.validator').isFormValid()) {
							_operateStore(operationVo);
						};
					} else if (constants.operation.EDIT === oper) {
						_validateStoreForm('#edit-store-modal');
						if($('#edit-store-modal').data('amui.validator').isFormValid()) {
							_operateStore(operationVo);
						};
					} else {
						_operateStore(operationVo);
					}

		        });
	        }
        }
	}]);
	

	flightDirectives.directive('adminChildData', ['UrlService', 'UtilService', '$compile','ChildrenService',
									 function(UrlService, UtilService, $compile, ChildrenService) {
		var $scope, 
			filter = {
				'pagesize': 10,
				'pno': 1,
				'search': ''
			}
		function _renderchildPager (data) {
			var $record = $('.child-container .child-total-record'),
			    $element = $('.child-container .child-pager-container');
			UtilService.renderPagerContainer($element, $record, data, $scope, $compile);
		}

		function _changechildrenPages (event) {
	    	var $ele = $(this);
	    	filter.pagesize = $ele.data('value');
	    	_renderchildrenList(filter);
        }

        function _searchchildrenPages (event) {
	    	var $ele = $(this), search = $ele.val(), 
	    		pagesize = $('.am-selected-list .am-checked').data('value');
	    	filter.pagesize = pagesize;
	    	filter.search =  search;
	    	_renderchildrenList(filter);
	    }

	     function _forwardchildrenPages (event) {
	    	var $ele = $(this), pno = $ele.find('a').text(), 
	    	    pagesize = $('.am-selected-list .am-checked').data('value');
	        filter.pagesize = pagesize;
	    	filter.pno =  pno;
	    	_renderchildrenList(filter);
	    }

	    function _renderchildrenList (filter) {
	    	var apiURL = url.childrenListURL() +'?userId=0&accessToken='+$scope.accessToken+'&filter=' + escape(JSON.stringify(filter));
	    	UrlService.doRequest(apiURL, 'GET').success(function(response, status) {
	  		    if (response.jsonResponse.statusCode == constants.responseCode.SUCCESS) {
	  		       $scope.childrens = response.jsonResponse.response.data;
	  	        } else if (response.statusCode == constants.responseCode.LOGIN_ANOTHER_DEVICE) {
	  	          
	  	        }
            });
	    }

	    function  _selectAllchildren (event) {
	    	var $ele = $(this);
	    	if ($ele.prop('checked')) {
	    	    $('.select-single-record').prop('checked', 'checked');
	    	} else {
	    		$('.select-single-record').each(function() {
	    			$(this).prop('checked', false);
	    		})
	    	}
	    }
	    function _changeChildPagesize (event) {
	    	var $ele = $(this), params = {
	    			'userId': 0,
		        	'accessToken': $scope.accessToken,
		        	'filter': {
			        	'pagesize': 10,
			        	'pno': 1,
			        	'search': ''
			        }
                };
	    	params.filter.pagesize = $ele.data('value');
	    	params.filter.pno = $scope.children.currentPage;
	    	_renderChildrenList(params);
        }

        function _renderChildrenList (params) {
	    	ChildrenService.listChildren(params).success(function(response, status) {
	  		    if (response.jsonResponse.statusCode == constants.responseCode.SUCCESS) {
	  		       $scope.children = response.jsonResponse.response.data;
	  	        } else if (response.statusCode == constants.responseCode.LOGIN_ANOTHER_DEVICE) {
	  	          // childService.Child.logout();
	  	          //window.location.href = constants.pages.guide;
	  	        }
            });
	    }
	    function _editLevel(){
	    	$('#edit-childLevel-modal').modal({
              width: 400,
              height: 250
           });
	    }
	    function _editCoin(){
	    	$('#edit-childCoin-modal').modal({
              width: 400,
              height: 250
           });
	    }
	    function _editSessionCount(){
	    	$('#edit-child-allowSessionCount-modal').modal({
              width: 400,
              height: 250
           });
	    }

	    function _viewMission(){
	    	$('#view-mission-child-modal').modal({
				width: 1000,
				height: 850
			});
	    }

	    function _findAtem(){
	    	$('#add-Item-modal').modal(
	    		{
	    			width: 1000,
	    			height: 850
	    		}
	    	);
	    }

	     function _info(){
	    	$('#child-inventorys-modal').modal();
	    }

		return {
	        link: function(scope, ele, attrs, c) {
		        var self = $(ele);
		        $scope = scope;
		        scope.$watch('children', function(newVal, oldVal) {
		        	scope.children = newVal;
		            if (newVal) {
		            	_renderchildPager(newVal);
		            }
		        });
			    $('.child-container .select-all-child').on('click', _selectAllchildren);
			    $('.child-page-list').on('click', '.am-selected-list li', _changeChildPagesize);
			    $('.child-container').on('click', '.childLevel button', _editLevel);
			    $('.child-container').on('click', '.childCoin a', _editCoin);
			    $('.child-container').on('click', '.childSessionCount a', _editSessionCount);
			    $('.child-container').on('click', '.viewMission', _viewMission);
			    $('.child-container').on('click', '.find-atem', _findAtem);
			    $('.child-container').on('click', '.info', _info);

	        }
        }
	}]);




	flightDirectives.directive('adminChildMissionData', ['UrlService', 'UtilService', '$compile', 'ChildrenService',
			function(UrlService, UtilService, $compile, ChildrenService) {
		var $scope, 
			filter = {
				'pagesize': 8,
				'pno': 1,
				'search': ''
			}
		function _renderchildMissionPager (data) {
			var $record = $('.child-mission-total-record'),
			    $element = $('.child-mission-pager-container');
			UtilService.renderPagerContainer($element, $record, data, $scope, $compile);
		}

		
        function _searchchildMissionPages(event) {
	    	var $ele = $(this), search = $ele.val(), 
	    		pagesize = 8;
	    	filter.pagesize = pagesize;
	    	filter.search =  search;
	    	_renderchildMissionList(filter);
	    }

	    function _forwardchildMissionPages (event) {
	    	var $ele = $(this), pno = $ele.find('a').text(), 
	    	    pagesize = 8;
	        filter.pagesize = pagesize;
	    	filter.pno =  pno;
	    	_renderchildMissionList(filter);
	    }
	    function _prechildMissionPages (event) {
	        filter.pagesize = 8;
	    	filter.pno =  $scope.missions.currentPage - 1;
	    	_renderchildMissionList(filter);
	    }
	    function  _nextchildMissionPages (event) { 
	        filter.pagesize = 8;
	    	filter.pno =  $scope.missions.currentPage + 1 ;
	    	_renderchildMissionList(filter);
	    }


	    function _renderchildMissionList (filter) {
	    	var params = {
  				'id': $scope.id,
       	       'accessToken': $scope.accessToken,
       	       'filter': filter
      		  }     
	    	ChildrenService.listChildrenView(params).success(function(response, status) {
	  		    if (response.jsonResponse.statusCode == constants.responseCode.SUCCESS) {
	  		       $scope.missions = response.jsonResponse.response.data;
	  	        } else if (response.statusCode == constants.responseCode.LOGIN_ANOTHER_DEVICE) {
	  	          
	  	        }
            });
	    }

	    function _selectAllchildren (event) {
	    	var $ele = $(this);
	    	if ($ele.prop('checked')) {
	    	    $('.select-single-record').prop('checked', 'checked');
	    	} else {
	    		$('.select-single-record').each(function() {
	    			$(this).prop('checked', false);
	    		})
	    	}
	    }

		return {
	        link: function(scope, ele, attrs, c) {
		        var self = $(ele);
		        $scope = scope;
		        scope.$watch('missions', function(newVal, oldVal) {
		        	scope.missions = newVal;
		            if (newVal) {
		            	_renderchildMissionPager(newVal);
		            }
		        });

		       
			    $('.child-filter').on('keyup', '.search-mission', _searchchildMissionPages);
			    $('.child-mission-pager-container').on('click', '.active-pno', _forwardchildMissionPages);
			    $('.child-mission-pager-container').on('click', '.pre-page a', _prechildMissionPages);
			    $('.child-mission-pager-container').on('click', '.next-page a', _nextchildMissionPages);
			    $('.select-all-missiom-child').on('click', _selectAllchildren);
	        }
        }
	}]);

	
	flightDirectives.directive('adminChildItemData', ['UrlService', 'UtilService', '$compile', 'ChildrenService',
												 function(UrlService, UtilService, $compile, ChildrenService) {
		var $scope, 
			filter = {
				'pagesize': 8,
				'pno': 1,
				'search': ''
			}

		function _prechilditemPages (event) {
		    filter.pagesize = 8;
			filter.pno =  $scope.items.currentPage - 1;
			_renderchildItemList(filter);
		}
		function _nextchilditemPages (event) { 
		    filter.pagesize = 8;
			filter.pno =  $scope.items.currentPage + 1 ;
			_renderchildItemList(filter);
		}
		function _renderchildItemPager (data) {
			var $record = $('.child-item-total-record'),
			    $element = $('.child-item-pager-container');
			UtilService.renderPagerContainer($element, $record, data, $scope, $compile);
		}

	     function _forwardchildItemPages (event) {
	    	var $ele = $(this), pno = $ele.find('a').text(), 
	    	    pagesize = 8;
	        filter.pagesize = pagesize;
	    	filter.pno =  pno;
	    	_renderchildItemList(filter);
	    }

	    function _selectAllItems (event) {
	    	var $ele = $(this);
	    	if ($ele.prop('checked')) {
	    	    $('.select-single-record').prop('checked', 'checked');
	    	} else {
	    		$('.select-single-record').each(function() {
	    			$(this).prop('checked', false);
	    		})
	    	}
	    }

	    function _operItems(event){
	    	var itemIds = [];
	    	$(".check-select input:checked").each(function(){
  			  if(this.checked){
  			  	itemIds.push($(this).val());
   			 };
   			});
   			var param = {
   				 'id': $scope.id,
   				 'itemIds': itemIds,
   				 'accessToken': $scope.accessToken,
   				 'num':$scope.num,
   			};
   			ChildrenService.childrenItemOper(param).success(function(response, status) {
   				 if (response.jsonResponse.statusCode == constants.responseCode.SUCCESS) {
	  		    	alert("ADD SUCCESS");
	  	        } else if (response.statusCode == constants.responseCode.LOGIN_ANOTHER_DEVICE) {
	  	          
	  	        }
   			});
	    }

	    function _renderchildItemList (filter) {
	    	var params = {
       	       'accessToken': $scope.accessToken,
       	       'filter': filter
      		  };
	    	ChildrenService.listChildrenAddItem(params).success(function(response, status) {
	  		    if (response.jsonResponse.statusCode == constants.responseCode.SUCCESS) {
	  		       $scope.items = response.jsonResponse.response.data;
	  	        } else if (response.statusCode == constants.responseCode.LOGIN_ANOTHER_DEVICE) {
	  	          
	  	        }
            });
	    }

		return {
	        link: function(scope, ele, attrs, c) {
		        var self = $(ele);
		        $scope = scope;
		        scope.$watch('items', function(newVal, oldVal) {
		        	scope.items = newVal;
		            if (newVal) {
		            	_renderchildItemPager(newVal);
		            }
		        });
		        $('.am-modal-bd').on('click', '.select-all-record', _selectAllItems);
			    $('.child-item-pager-container').on('click', '.active-pno', _forwardchildItemPages);
			    $('.child-item-pager-container').on('click', '.pre-page a', _prechilditemPages);
			    $('.child-item-pager-container').on('click', '.next-page a', _nextchilditemPages);
			    $('#view-mission-child-table').on('click', '.number', _operItems);
	        }
        }
	}]);


	flightDirectives.directive('adminChildInventoryData', ['UrlService', 'UtilService', '$compile', 'ChildrenService',
														function(UrlService, UtilService, $compile, ChildrenService) {
		var $scope, 
			filter = {
				'pagesize': 4,
				'pno': 1,
				'search': ''
			}
		function _renderChildrenInventoryPager (data) {
			var $record = $('.child-inventory-total-record'),
			    $element = $('.child-inventory-pager-container');
			UtilService.renderPagerContainer($element, $record, data, $scope, $compile);
		}
	     function _forwardChildrenInventoryPages (event) {
	    	var $ele = $(this), pno = $ele.find('a').text(), 
	    	    pagesize = 4;
	        filter.pagesize = pagesize;
	    	filter.pno =  pno;
	    	_renderchildInventoryList(filter);
	    }

	    function _renderchildInventoryList (filter) {
	    	var param = {
		 		'id':$scope.userId,
		 		'accessToken': $scope.accessToken,
       	       	'filter': filter
		 		};
	    	ChildrenService.findInventory(param).success(function(response, status) {
	  		    if (response.jsonResponse.statusCode == constants.responseCode.SUCCESS) {
	  		       $scope.inventorys = response.jsonResponse.response.data;
	  	        } else if (response.statusCode == constants.responseCode.LOGIN_ANOTHER_DEVICE) {
	  	          
	  	        }
            });
	    }
	    function _prechildInventoryPages (event) {
		    filter.pagesize = 4;
			filter.pno =  $scope.inventorys.currentPage - 1;
			_renderchildInventoryList(filter);
		}
		function _nextchildInventoryPages (event) { 
		    filter.pagesize = 4;
			filter.pno =  $scope.inventorys.currentPage + 1 ;
			_renderchildInventoryList(filter);
		}
		return {
	        link: function(scope, ele, attrs, c) {
		        var self = $(ele);
		        $scope = scope;
		        scope.$watch('inventorys', function(newVal, oldVal) {
		        	scope.items = newVal;
		            if (newVal) {
		            	_renderChildrenInventoryPager(newVal);
		            }
		        });
			    $('.child-inventory-pager-container').on('click', '.active-pno', _forwardChildrenInventoryPages);
			    $('.child-inventory-pager-container').on('click', '.pre-page a', _prechildInventoryPages);
			    $('.child-inventory-pager-container').on('click', '.next-page a', _nextchildInventoryPages);
	        }
        }
	}]);

	flightDirectives.directive('adminChildGameSessionData', ['UrlService', 'UtilService', '$compile', 'ChildrenService',
																function(UrlService, UtilService, $compile, ChildrenService) {
		var $scope, 
			filter = {
				'pagesize': 5,
				'pno': 1,
				'search': ''
			}
		function _renderChildrenGameSessionPager (data) {
			var $record = $('.child-game-session-total-record'),
			    $element = $('.child-game-session-pager-container');
			UtilService.renderPagerContainer($element, $record, data, $scope, $compile);
		}
	     function _forwardChildrenGameSessionPages (event) {
	    	var $ele = $(this), pno = $ele.find('a').text(), 
	    	    pagesize = 5;
	        filter.pagesize = pagesize;
	    	filter.pno =  pno;
	    	_renderchildGameSessionList(filter);
	    }

	    function _renderchildGameSessionList (filter) {
	    	var param = {
		 		'id':$scope.userId,
		 		'accessToken': $scope.accessToken,
       	       	'filter': filter
		 		};
	    	ChildrenService.findGameSession(param).success(function(response, status) {
	  		    if (response.jsonResponse.statusCode == constants.responseCode.SUCCESS) {
	  		       $scope.gamesessions = response.jsonResponse.response.data;
	  	        } else if (response.statusCode == constants.responseCode.LOGIN_ANOTHER_DEVICE) {
	  	          
	  	        }
            });
	    }
	    function _prechildGameSessionPages (event) {
		    filter.pagesize = 4;
			filter.pno =  $scope.gamesessions.currentPage - 1;
			 _renderchildGameSessionList(filter);
		}
		function _nextchildGameSessionPages (event) { 
		    filter.pagesize = 4;
			filter.pno =  $scope.gamesessions.currentPage + 1 ;
			 _renderchildGameSessionList(filter);
		}
		return {
	        link: function(scope, ele, attrs, c) {
		        var self = $(ele);
		        $scope = scope;
		        scope.$watch('gamesessions', function(newVal, oldVal) {
		        	scope.items = newVal;
		            if (newVal) {
		            	_renderChildrenGameSessionPager(newVal);
		            }
		        });
			    $('.child-game-session-pager-container').on('click', '.active-pno', _forwardChildrenGameSessionPages);
			    $('.child-game-session-pager-container').on('click', '.pre-page a', _prechildGameSessionPages);
			    $('.child-game-session-pager-container').on('click', '.next-page a', _nextchildGameSessionPages);
	        }
        }
	}]);

    /********************************************************** Item module  ****************************************************************/

	flightDirectives.directive('adminItemData', ['UtilService', 'ItemService', 'AdminService', '$compile', function(UtilService, ItemService, AdminService, $compile) {
		var $scope;

		function _renderItemPager (data) {
			var $record = $('.item-container .item-total-record'),
			    $element = $('.item-container .item-pager-container');
			UtilService.renderPagerContainer($element, $record, data, $scope, $compile);
		}

	    function _selectAllItems (event) {
	    	var $ele = $(this);
	    	if ($ele.prop('checked')) {
	    	    $('.select-single-record').prop('checked', 'checked');
	    	} else {
	    		$('.select-single-record').each(function() {
	    			$(this).prop('checked', false);
	    		})
	    	}
	    }

	    function _changeItemPagesize (event) {
	    	var $ele = $(this), params = {
		        	'accessToken': $scope.accessToken,
		        	'filter': {
			        	'pagesize': 10,
			        	'pno': 1,
			        	'search': ''
			        }
                };
	    	params.filter.pagesize = $ele.data('value');
	    	params.filter.pno = $scope.items.currentPage;
	    	_renderItemList(params);
        }

        function _lockAndUnlockItem (event) {
	    	var $ele = $(this), id = $ele.data('id'),
		    	operationVo = {
							'oper': $ele.data('oper'), 
							'id': $ele.data('id'), 
							'data': {
							}
						};

	    	ItemService.operateItem({'accessToken': $scope.accessToken, 'operate': JSON.stringify(operationVo)}).success(function(data){
	    		if (data.jsonResponse.statusCode == constants.responseCode.SUCCESS) {
	    			if ($ele.hasClass('am-btn-danger')) {
	    				$ele.removeClass('am-btn-danger').addClass('am-btn-success');
	    				$ele.text('Unlock');
	    			} else {
	    				$ele.removeClass('am-btn-success').addClass('am-btn-danger');
	    				$ele.text('Locked');
	    			}
	    		}
	    	});
	    }

	    function _renderItemList (params) {
	    	ItemService.listItems(params).success(function(response, status) {
	  		    if (response.jsonResponse.statusCode == constants.responseCode.SUCCESS) {
	  		       $scope.items = response.jsonResponse.response.data;
	  	        } else if (response.statusCode == constants.responseCode.LOGIN_ANOTHER_DEVICE) {
	  	           AdminService.Admin.logout();
	  	           window.location.href = constants.pages.login;
	  	        }
            });
	    }
	   
		return {
	        link: function(scope, ele, attrs, c) {
		        var self = $(ele);
		        $scope = scope;
		        scope.$watch('items', function(newVal, oldVal) {
		        	scope.items = newVal;
		            if (newVal) {
		            	_renderItemPager(newVal);
		            }
		        });

		        $('.item-page-list').on('click', '.am-selected-list li', _changeItemPagesize);
			    $('.item-container #item-table').on('click', '.select-all-item', _selectAllItems);
			    $('.item-container #item-table').on('click', '.item-operate', _lockAndUnlockItem);

	        }
        }
	}]);

	flightDirectives.directive('adminEditItem', ['UtilService', 'ItemService', function(UtilService, ItemService) {
		return {
	        link: function(scope, ele, attrs, c) {
		        var self = $(ele);
		        ele.on('click', function(e) {
		        	var $selectItem = $('#item-table input[name=select-single-item]:checked');
		        	if ($selectItem.length) {
				        var $item = $selectItem.parent().parent();
				        var itemId = $item.find('.itemId').text();
				        $('#edit-item-modal button').data('id', itemId);
				        ItemService.getItemById({'itemId': itemId, 'accessToken': scope.accessToken}).success(function(response, status){
				        	if (response.jsonResponse.statusCode == constants.responseCode.SUCCESS) {
				        		scope.item = response.jsonResponse.response;
				        	}
				        })
				        UtilService.showModal($('#edit-item-modal'));
		        	} else {
		        		UtilService.showModal($('#item-warning'));
		        	}
		        	
		        });
	        }
        }
	}]);

	flightDirectives.directive('adminDeleteItem', ['UtilService', function(UtilService) {
		return {
	        link: function(scope, ele, attrs, c) {
		        var self = $(ele);
		        ele.on('click', function(e) {
		        	var $selectItem = $('#item-table input[name=select-single-item]:checked');
		        	if ($selectItem.length) {
				        var $item = $selectItem.parent().parent();
				        var itemId = $item.find('.itemId').text();
				        $('#delete-item-modal .delete-item-btn').data('id', itemId);
				        UtilService.showModal($('#delete-item-modal'));
		        	}  else {
		        		UtilService.showModal($('#item-warning'));
		        	}
		        	
		        });
	        }
        }
	}]);

	flightDirectives.directive('adminOperateItem', ['ItemService', 'UtilService', function(ItemService, UtilService) {
		var $scope;
		function _refreshItems () {
			var filter = {'pagesize': $scope.pagesize, 
						  'pno': 1, 
						  'search': ''
						 };
	    	ItemService.listItems({'accessToken': $scope.accessToken, 'filter': filter}).success(function(response, status) {
	  		    if (response.jsonResponse.statusCode == constants.responseCode.SUCCESS) {
	  		       $scope.items = response.jsonResponse.response.data;
	  	        } else if (response.statusCode == constants.responseCode.LOGIN_ANOTHER_DEVICE) {
	  	          
	  	        }
            });
		}

		function _operateItems (item) {
		    ItemService.operateItem({'accessToken': $scope.accessToken, 'operate': JSON.stringify(item)}).success(function(response, status) {
			  	if (response.jsonResponse.statusCode == constants.responseCode.SUCCESS) {
			  		if (response.jsonResponse.response.meta.code == 200) {
					  	$('.am-close-spin').click();
					  	_refreshItems();
			  		}
			  	} else if (response.statusCode == constants.responseCode.LOGIN_ANOTHER_DEVICE) {
			  	         
			  	}
	        });
		}

		return {
	        link: function(scope, ele, attrs, c) {
	        	$scope = scope;
		        var self = $(ele);
		        ele.on('click', function(e) {
		        	var oper = self.data('oper'), operationVo = {
						'oper': oper, 
						'id': self.data('id'), 
						'data': {
						}
					};	

					if(constants.operation.ADD === oper) {
						UtilService.validateForm('#add-item-form');
						if($('#add-item-form').data('amui.validator').isFormValid()) {
							operationVo.data = $scope.item;
							_operateItems(operationVo);
							UtilService.clearValidForm('#add-item-form');
							$scope.item = null;
						};
					} else if (constants.operation.EDIT === oper) {
						UtilService.validateForm('#edit-item-form');
						if($('#edit-item-form').data('amui.validator').isFormValid()) {
							operationVo.data = $scope.item;
							_operateItems(operationVo);
							UtilService.clearValidForm('#edit-item-form');
							$scope.item = null;						
						};
					} else {
						_operateItems(operationVo);
					}

		        });
	        }
        }
	}]);
	/********************************************************** parents ****************************************************************/
	flightDirectives.directive('adminParentData', ['UtilService', 'ParentService', 'AdminService', '$compile', 
				function(UtilService, ParentService, AdminService, $compile) {

		var $scope;	
		function _renderParentsPager (data) {
			var $record = $('.parent-total-record'),
			    $element = $('.parent-pager-container');
			UtilService.renderPagerContainer($element, $record, data, $scope, $compile);
		}

		function  _changeParentPagesize(event){
			
		}

		function _forwardparentPages(event){
			var filter = {
        		'pagesize': $scope.parents.pagesize, 
				'pno':  event.target.text, 
				'search': $scope.search
        	};
			_renderParentItemList (filter);
		}

		function _preparentPages(){
			var filter = {
        		'pagesize': $scope.parents.pagesize, 
				'pno':  $scope.parents.currentPage-1, 
				'search': $scope.search
        	};
			_renderParentItemList (filter);
		}

		function  _nextparentPages(){
			var filter = {
        		'pagesize': $scope.parents.pagesize, 
				'pno':  $scope.parents.currentPage+1, 
				'search': $scope.search
        	};
			_renderParentItemList (filter);

		}

		function _renderParentItemList (filter) {
			 var params = {
                'userId': 0,
               'accessToken':$scope.accessToken,
               'filter': filter,
        	} ;
			ParentService.parentList(params).success(function(response, status) {
			    if (response.jsonResponse.statusCode == constants.responseCode.SUCCESS) {
			       $scope.parents = response.jsonResponse.response.data;
			    } else if (response.statusCode == constants.responseCode.LOGIN_ANOTHER_DEVICE) {
			       AdminService.Admin.logout();
			       window.location.href = constants.pages.login;
			    }
			});
		 }

		  function _changeUserEnable(event){
        	var filter = {
        		'pagesize': $scope.pagesize, 
				'pno': $scope.currentPage, 
				 'search': ''
        	},param = {
        		'userId':$scope.id
        	};
        	if(event.target.innerText=='Enable'){
        		ParentService.parentChangeEnable(param).success(function(response, status) {
        			 if (response.jsonResponse.statusCode == constants.responseCode.SUCCESS) {
        			 	_renderParentItemList (filter);
        			 }
        		})
        	}else{
        		ParentService.parentChangeDisable(param).success(function(response, status) {
        			 if (response.jsonResponse.statusCode == constants.responseCode.SUCCESS) {
        			 	_renderParentItemList (filter);
        			 }
        		})
        	}
        }
         function _changeAbleDebug(event){
         	var filter = {
        		'pagesize': $scope.pagesize, 
				'pno': $scope.currentPage, 
				 'search': ''
        	},param = {
        		'userId':$scope.id
        	};
        	if(event.target.innerText=='Enable Debug'){
        		ParentService.parentChangeDebugEnable(param).success(function(response, status) {
        			 if (response.jsonResponse.statusCode == constants.responseCode.SUCCESS) {
        			 	_renderParentItemList (filter);
        			 }
        		})
        	}else{
        		ParentService.parentChangeDebugDisable(param).success(function(response, status) {
        			 if (response.jsonResponse.statusCode == constants.responseCode.SUCCESS) {
        			 	_renderParentItemList (filter);
        			 }
        		})
        	}
         }
         function _addChild(event){
         	$('#child-modal').modal(
         		{
	    			width: 500,
	    			height: 600
	    		}
         	);
         }	

		return {
	        link: function(scope, ele, attrs, c) {
		        var self = $(ele);
		        $scope = scope;
		        scope.$watch('parents', function(newVal, oldVal) {
		        	scope.parents = newVal;
		            if (newVal) {
		            	_renderParentsPager(newVal);
		            }
		        });
		        $('.am-table-hover').on('click','#parent-accountState', _changeUserEnable);
		        $('.am-table-hover').on('click','#parent-enableDebug', _changeAbleDebug);
		        $('.am-table-hover').on('click','.add-child', _addChild);
		        $('.parent-page-list').on('click', '.am-selected-list li', _changeParentPagesize);
		        $('.parent-pager-container').on('click', '.active-pno', _forwardparentPages);
			    $('.parent-pager-container').on('click', '.pre-page a', _preparentPages);
			    $('.parent-pager-container').on('click', '.next-page a', _nextparentPages);

	        }
        }
	}]);
	
	flightDirectives.directive('adminsAdminData', ['UtilService', 'AdminsService', 'AdminService', '$compile', 
				function(UtilService, AdminsService, AdminService, $compile) {

		var $scope;	
		function _renderAdminsPager (data) {
			var $record = $('.admin-total-record'),
			    $element = $('.admin-pager-container');
			UtilService.renderPagerContainer($element, $record, data, $scope, $compile);
		}

		function  _changeAdminPagesize(event){
				var $ele = $(this), filter = {
        		'pagesize': $ele.data('value'), 
				'pno':   $scope.admins.currentPage, 
				'search': $scope.search
        	};
	    	_renderAdminItemList(filter);
		}

		function _forwardadminPages(event){
			var filter = {
        		'pagesize': $scope.admins.pagesize, 
				'pno':  event.target.text, 
				'search': $scope.search
        	};
			 _renderAdminItemList(filter);
		}

		function _preadminPages(){
			var filter = {
        		'pagesize': $scope.admins.pagesize, 
				'pno':  $scope.admins.currentPage-1, 
				'search': $scope.search
        	};
			_renderAdminItemList(filter);
		}

		function  _nextadminPages(){
			var filter = {
        		'pagesize': $scope.admins.pagesize, 
				'pno':  $scope.admins.currentPage+1, 
				'search': $scope.search
        	};
			_renderAdminItemList(filter);

		}

		function _renderAdminItemList (filter) {
			 var params = {
               'accessToken':$scope.accessToken,
               'filter': filter,
        	} ;
			AdminsService.adminList(params).success(function(response, status) {
			    if (response.jsonResponse.statusCode == constants.responseCode.SUCCESS) {
			       $scope.admins = response.jsonResponse.response.data;
			    } else if (response.statusCode == constants.responseCode.LOGIN_ANOTHER_DEVICE) {
			       AdminService.Admin.logout();
			       window.location.href = constants.pages.login;
			    }
			});
		 }

		

		return {
	        link: function(scope, ele, attrs, c) {
		        var self = $(ele);
		        $scope = scope;
		        scope.$watch('admins', function(newVal, oldVal) {
		        	scope.admins = newVal;
		            if (newVal) {
		            	_renderAdminsPager(newVal);
		            }
		      
		        $('.admin-page-list').on('click', '.am-selected-list li', _changeAdminPagesize);
		        $('.admin-pager-container').on('click', '.active-pno', _forwardadminPages);
			    $('.admin-pager-container').on('click', '.pre-page a', _preadminPages);
			    $('.admin-pager-container').on('click', '.next-page a', _nextadminPages);

	        })}
        }
	}]);

	

	


	flightDirectives.directive('adminEditPolicy', ['UtilService', function(UtilService) {
		return {
	        link: function(scope, ele, attrs, c) {
		        var self = $(ele);
		        ele.on('click', function(e) {
		        	e.preventDefault();
		        	UtilService.renderNicEditor(scope);
		        });
	        }
        }
	}]);

	flightDirectives.directive('adminUpdatePolicy', ['UtilService', function(UtilService) {
		return {
	        link: function(scope, ele, attrs, c) {
		        var self = $(ele);
		        ele.on('click', function(e) {
		        	var editor = scope.editor;
		        	if (editor) {
		        		console.log(12);
		        		/*editor.removeInstance('policy');
		        		scope.editor = null;*/
		        	}
		        });
	        }
        }
	}]);

});
